App.circulates = function() {

        //Bar Chart 2
    var widget_barchart2 = function (data, element){

      var color1 = App.color.alt3;
      var color2 = tinycolor( App.color.alt3 ).lighten( 22 ).toString();

      /**
      var data = [
        {
          data: [
            [0, 7], [1, 13], [2, 17], [3, 20], [4, 26], [5, 37], [6, 35], [7, 28], [8, 38], [9, 38], [10, 32]
          ],
          label: "Page Views"
        }/**,
        {
          data: [
            [0, 15], [1, 10], [2, 15], [3, 25], [4, 30], [5, 29], [6, 25], [7, 33], [8, 45], [9, 43], [10, 38]
          ],
          label: "Unique Visitor"
        }
      ];
      **/
      console.log(element);
      var plot_statistics = $.plot( element || $("#bar-chart2"), data, {
        series: {
          bars: {
            order: 3,
            align: 'center',
            show: true,
            lineWidth: 7, 
            barWidth: 100*60*1000, 
            fill: true,
            fillColor: {
              colors: [{
                opacity: 1
              }, {
                opacity: 1
              }]
            } 
          },
          shadowSize: 2
        },
        legend:{
          show: true
        },
        grid: {
          labelMargin: 10,
          axisMargin: 300,
          hoverable: true,
          clickable: true,
          tickColor: "rgba(0,0,0,0.15)",
          borderWidth: 0
        },
        colors: [color1, color2],
        xaxis: {
          ticks: 15,
          mode: "time",
          minTickSize: [1, "day"],
          timeformat: "%m/%d",//"%y/%m/%d",
          tickDecimals: 1
        },
        yaxis: {
          ticks: 5,
          tickDecimals: 0
        }
      });

      //console.log('dfdfd');
    }

  /**
  App.loading('stat/circulates4day?size=9&action=LOAN', function(res) {
      //console.log(res);
    //barchart(res);
    //update_holding_list(res);
  });
  **/

  $('#btn-cir-left, #btn-cir-right').click(function() {

      $.extend($.gritter.options, { 
          fade_in_speed: 'medium', // how fast notifications fade in (string or int)
          time: 2000 // hang on the screen for...
      });

      var p = $(this).data('page');
      var c = loading_circulate.page;
      c = c + p;
      if (c > 0) {
        loading_circulate(c);
        $.gritter.add({
          //title: 'Success',
          text: '加载数据中...',
          class_name: 'color info'
        });
      }
      else {
        $.gritter.add({
          //title: 'Success',
          text: '暂无数据...',
          class_name: 'color info'
        });
      }
  });


  var loading_circulate = function (page, element) {

      loading_circulate.page = page || 1;

      axios.all([
        axios.get('stat/circulates4day?size=10&action=LOAN&page=' + page),
        axios.get('stat/circulates4day?size=10&action=RETURN&page=' + page)
      ])
      .then(axios.spread( function(loans, returns) {

        var datasets = [{data:[], label: "借阅量"},{data:[], label: "还书量"}];

        //console.log(loans, returns);

        if (loans && loans.status == 200 && loans.data.status == 1) {
            datasets[0]['data'] = [];
            var i = 0;
            loans.data.data.data.list.forEach(function(item) {
              var time  = new Date(item.MTIME);//.format('YYYY/MM/DD');
              //var time = time.substr(0,4) + "-" + time.substr(4,2) + "-" + time.substr(6,2);
              //console.log(time, item.TOTAL);
              datasets[0]['data'].push([time, item.TOTAL])
            });
        }

        if (returns && returns.status == 200 && returns.data.status == 1) {
            datasets[1]['data'] = [];
            var i = 0;
            returns.data.data.data.list.forEach(function(item) {
              var time  = new Date(item.MTIME);//.format('YYYY/MM/DD');
              //console.log(time, item.TOTAL);
              datasets[1]['data'].push([time, item.TOTAL])
            });
        }

        //console.log(datasets);
        widget_barchart2(datasets, element);
       }))
      .catch(function(res){
          console.log(res);
      })
    };

    loading_circulate(1);


    var loading_circulate_total = function() {
       axios.get('stat/circulates4lib')
        .then(function(res){
          $('#cir-total-table td:eq(0)').html(res.data.data.TOTAL);
          $('#cir-total-table td:eq(1)').html(res.data.data.LOAN);
          $('#cir-total-table td:eq(2)').html(res.data.data.RETURN);
          $('#cir-total-table td:eq(3)').html(res.data.data.RENEW);
          console.log(res);
        });
    };
    loading_circulate_total();


    var loading_circulate_month = function() {
      axios.get('stat/circulates4month')
        .then(function (res) {
        if (res && res.status == 200 && res.data.status == 1) {
          data = [];
          var total = parseInt(res.data.detail);
          total = total > 1 ? total : 10000;
          console.log(total);

          var num = 0;
          res.data.data.data.forEach(function(v) {
            if (++num>20)  return;
            $("#circ-month-table").append("<tr><td>" 
              + v.MTIME + "</td><td class='number'>" 
              + v.TOTAL + "</td></tr>");
          }) ;
        }
      })
      .catch(function(e){console.log(e);});
    }
    loading_circulate_month();

    var loading_circulate_top = function() {
      axios.get('stat/circulates4top')
        .then(function (res) {
        if (res && res.status == 200 && res.data.status == 1) {
          data = [];
          var total = parseInt(res.data.detail);
          total = total > 1 ? total : 10000;
          //console.log(total);

          var num = 0;
          res.data.data.data.list.forEach(function(v) {
            if (++num>10)  return;
            $("#circ-top-table").append("<tr><td>" 
              + v.Biblio.TITLE + "</td><td class='number'>" 
              + v.TOTAL + "</td></tr>");
          }) ;
        }
      })
      .catch(function(e){console.log(e);});
    }
    loading_circulate_top();

    var loading_circulate_last = function() {
      axios.get('stat/circulates4zero?size=20')
        .then(function (res) {
        if (res && res.status == 200 && res.data.status == 1) {
          data = [];
          var total = parseInt(res.data.detail);
          total = total > 1 ? total : 10000;
          console.log(total);

          var num = 0;
          res.data.data.data.list.forEach(function(v) {
            if (++num>10)  return;
            $("#circ-last-table").append("<tr><td>" 
              + v.TITLE + "</td><td class='number'>" 
              + v.BOOKRECNO + "</td></tr>");
          }) ;
        }
      })
      .catch(function(e){console.log(e);});
    }
    loading_circulate_last();


    var radar_chart = function(res){

     /**
       * Randomize array element order in-place.
       * Using Durstenfeld shuffle algorithm.
       */
      function shuffleArray(array) {
        for (var i = array.length - 1; i > 0; i--) {
            var j = Math.floor(Math.random() * (i + 1));
            var temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
        return array;
      }

      var color1 = tinycolor( App.color.primary ).lighten( 6 );
      var color2 = tinycolor( App.color.alt4 ).lighten( 6.5 );

      var data = {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [
          /**{
            label: "My First dataset",
            fillColor: color2.setAlpha(.5).toString(),
            pointColor: color2.setAlpha(.8).toString(),
            strokeColor: color2.setAlpha(.8).toString(),
            highlightFill: color2.setAlpha(.75).toString(),
            highlightStroke: color2.toString(),
            data: [65, 59, 80, 81, 56, 55, 40]
          }
          ,**/
           {
            label: "My Second dataset",
            fillColor: color1.setAlpha(.5).toString(),
            pointColor: color1.setAlpha(.8).toString(),
            strokeColor: color1.setAlpha(.8).toString(),
            highlightFill: color1.setAlpha(.75).toString(),
            highlightStroke: color1.toString(),
            data: [28, 48, 40, 19, 86, 27, 90]
          }
        ]
      };

      if (res && res.data.status == 1) {
        data.labels = [];
        data.datasets[0].data = [];
        var i = 0;
        var dataset = {};
        var items = res.data.data.data.slice(1, 10);
        var items = shuffleArray(items);
        items.forEach(function(item) {
          //if (item.CAT == 'I') return;
          data.labels.push(item.CAT_NAME);
          data.datasets[0].data.push(item.TOTAL);
        });
        var top = res.data.data.data[0];
        $('#user-radar-n1 .number').html(top.CAT_NAME + ':' + top.TOTAL);
        $('#user-radar-n2 .number').html(res.data.detail);
      }

      var radarChart = new Chart( $("#user-radar-chart1").get(0).getContext("2d") ).Radar(data, {
        scaleShowLine : true,
        responsive: true,
        maintainAspectRatio: false,
        legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
      });
    }

    //barchart();
    axios.get('stat/personas').then(radar_chart);


    App.fn.loading_circulate = loading_circulate;
    return App;
};